var get_params = function ()
{
    var args = {};
    var query = window.location.search.substring(1); // 取查询字符串，如从 http://www.snowpeak.org/testjs.htm?a1=v1&a2=&a3=v3#anchor 中截出 a1=v1&a2=&a3=v3。
    var pairs = query.split("&"); // 以 & 符分开成数组
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('='); // 查找 "name=value" 对
        if (pos == -1){
            args[argname] = null;
        }
        else{
            var argname = pairs[i].substring(0,pos); // 取参数名
            var value = pairs[i].substring(pos+1); // 取参数值
            value = decodeURIComponent(value); // 若需要，则解码
            args[argname] = value; // 存成对象的一个属性
        }
    }
    return args; // 返回此对象
}

jQuery.extend(jQuery.validator.messages, {
        required: "必须填写",
        remote: "请修正该字段",
        email: "请输入正确格式的电子邮件",
        url: "请输入合法的网址",
        date: "请输入合法的日期",
        dateISO: "请输入合法的日期 (ISO).",
        number: "请输入合法的数字",
        digits: "只能输入整数",
        creditcard: "请输入合法的信用卡号",
        equalTo: "请再次输入相同的值",
        accept: "请输入拥有合法后缀名的字符串",
        maxlength: jQuery.format("请输入一个长度最多是 {0} 的字符串"),
        minlength: jQuery.format("请输入一个长度最少是 {0} 的字符串"),
        rangelength: jQuery.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
        range: jQuery.format("请输入一个介于 {0} 和 {1} 之间的值"),
        max: jQuery.format("请输入一个最大为 {0} 的值"),
        min: jQuery.format("请输入一个最小为 {0} 的值")
});

//手机校验
jQuery.validator.addMethod("mobile", function(value, element) {
     var length = value.length;
     var mobile = /^((1)+\d{10})$/;
     return (length == 11 && mobile.exec(value))? true:false;
 }, "请正确填写您的手机号码");

//邮编验证
 jQuery.validator.addMethod("postcode", function(value, element) {
     var postcode = /^[0-9]{6}$/;
     return (postcode.exec(value))?true:false;
 }, "请正确填写您的邮编");

//座机号码验证
 jQuery.validator.addMethod("phone", function(value, element) {
     var tel = /^[0-9\- \,]+$/;
     return (!value || tel.exec(value))?true:false;
 }, "请正确填写您的座机号码(数字减号空格逗号字符)");

$(document).ready(function() {
    "use strict";

    $('#suite').select2({
      minimumResultsForSearch: Infinity
    });
    var card_validate = $("#form-card-validate").validate({
        errorPlacement: function(error, element) {                        //错误信息位置设置方法
            //error.appendTo( element.parent() );                         //这里的element是录入数据的对象
            element.before(error);
        },
        rules: {
            validate_code: {
                remote: '/card/exchange/validate_code_verify'
            }
        },
        messages: {
            validate_code:{
                required: true,
                remote: '验证码不正确'
            }
        }
    });


    if (card_validate){
        var params = get_params();
        var errors = {}
        if(params['validate_code_error'] != undefined){
           errors['validate_code'] = '验证码错误';
        }
        if(params['code_or_password_error'] != undefined){
           errors['card_code'] = '券号或密码错误';
        }
        if(params['is_active_error'] != undefined){
           errors['card_code'] = '卡券未激活，请联系客服';
        }
        if(params['is_enabled_error'] != undefined){
           errors['card_code'] = '卡券已禁用，请联系客服';
        }
        card_validate.showErrors(errors);
    }


    var card_exchange_validate = $("#form-card-exchange").validate({
        errorPlacement: function(error, element) {                        //错误信息位置设置方法
            //error.appendTo( element.parent() );                         //这里的element是录入数据的对象
            element.before(error);
        }
    });

    if ($("#form-card-exchange").length>0) {

        var start_delivery_date = $('#delivery_date').attr('start_delivery_date');
        var end_delivery_date = $('#delivery_date').attr('end_delivery_date');


        var datepicker = $('#delivery_date').datepicker({
            format: "yyyy-mm-dd",
            startDate: start_delivery_date,
            endDate: end_delivery_date,
            language: "zh-CN",
            autoclose: true,
            todayHighlight: true,
            dateFormat: 'yy-mm-dd',
            minDate: new Date(Date.parse(start_delivery_date)),
            maxDate: new Date(Date.parse(end_delivery_date))
        });


        $('#province').change(function () {
            var province_id = $(this).val();
            if (province_id == '0') {
                $('#city').html('');
                $('#county').html('');
                return;
            }
            var data = {params: {province_id: province_id}};
            $('#city').html('<option value="">--请选择--</option>');
            $('#county').html('');
            $.ajax('/card/exchange/get_cities', {dataType: 'json', type: 'post', contentType: 'application/json', data: JSON.stringify(data)})
                .done(function (data) {
                    for (var i = 0; i < data.result.length; i++) {
                        var item = data.result[i];
                        $('#city').append("<option value='" + item.id + "'>" + item.name + "</option>");
                    }
                    if (data.result.length == 0) {
                        $('#city').html('');
                    }
                    if (data.result.length == 1) {
                        $('#city').val(data.result[0]['id']).trigger('change');
                    }
                })
        });

        $('#city').change(function () {
            var city_id = $(this).val();
            var data = {params: {city_id: city_id}};
            $('#county').html('<option value="">--请选择--</option>');
            $.ajax('/card/exchange/get_counties', {dataType: 'json', type: 'post', contentType: 'application/json', data: JSON.stringify(data)})
                .done(function (data) {
                    if (data.result.length > 0) {
                        $('.county-select').show();
                        $('#county').addClass('required');
                    }
                    else {
                        $('.county-select').hide();
                        $('#county').removeClass('required');
                    }
                    for (var i = 0; i < data.result.length; i++) {
                        var item = data.result[i];
                        $('#county').append("<option value='" + item.id + "'>" + item.name + "</option>");
                    }
                })
        });

        //可能时页面后退引起的只有省份值没有城市值，需要重新加载城市
        if ($('#province').val() && !$('#city').val()){
            $('#city').html('<option value="">--请选择--</option>');
            var data = {params: {province_id: $('#province').val()}};
            $.ajax('/card/exchange/get_cities', {dataType: 'json', type: 'post', contentType: 'application/json', data: JSON.stringify(data)})
                .done(function (data) {
                    for (var i = 0; i < data.result.length; i++) {
                        var item = data.result[i];
                        $('#city').append("<option value='" + item.id + "'>" + item.name + "</option>");
                    }
                    if (data.result.length == 0) {
                        $('#city').html('');
                    }
                    if (data.result.length == 1) {
                        $('#city').val(data.result[0]['id']).trigger('change');
                    }
                })
        }
    }

    //显示提货表单
    $('#show-card-exchange').click(function(){
        $(this).hide();
        $('.card-exchange-query').removeClass('hide');
        $('input[name=card_code]').focus();
    })

});


function search_express_detail(){
    //如果需要加载物流详情
    if ($('#express-delivery-detail').length == 1){
        var shipping_type = $('#express-delivery-detail').attr('data-shipping-type');
        var shipping_code = $('#express-delivery-detail').attr('data-shipping-code');
        $('#express-delivery-detail').html('<img src="/web/static/src/img/throbber.gif" width="16" height="16"/>');
        $('#express-delivery-detail').load('/card/exchange/express-delivery-detail?shipping_type=' + shipping_type + '&shipping_code=' + shipping_code);
    }
}

function reload_validate_code(){
    var d = new Date()
    $('#img_validate_code').attr('src', '/validate_code?' + d.getTime());
}